package com.xxxy.jsq.action.role;

import com.alibaba.fastjson2.JSONObject;
import com.xxxy.jsq.dao.RoleDao;
import com.xxxy.jsq.model.Page;
import com.xxxy.jsq.model.Role;


import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/getAllRolesPageServlet")
public class getAllRolesPageServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public getAllRolesPageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置字符编码，避免中文乱码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        // 创建角色模型和DAO对象
        Role model = new Role();
        RoleDao dao = new RoleDao();

        // 获取页面传递的查询参数
        String roleFlag = request.getParameter("cflag"); // 状态参数（与部门保持一致用"cflag"）
        String roleName = request.getParameter("cname"); // 角色名称参数（与部门保持一致用"cname"）

        // 设置查询条件到模型
        if (roleFlag != null && !roleFlag.equals("")) {
            model.setRoleFlag(roleFlag);
        }
        if (roleName != null && !roleName.equals("")) {
            model.setRoleName(roleName);
        }

        // 获取分页参数并初始化分页对象
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("limit");
        Page page = new Page();
        if (currentPage != null && !currentPage.equals("")
                && pageSize != null && !pageSize.equals("")) {
            page.setCurrentPage(Integer.parseInt(currentPage));
            page.setCount(Integer.parseInt(pageSize));
        }

        // 调用DAO查询分页数据和总记录数
        List<Role> roleList = dao.getAllDataByPage(model, page);
        int total = dao.getCount(model);

        // 构建JSON响应数据（符合LayUI表格组件要求的格式）
        JSONObject result = new JSONObject();
        result.put("code", 0); // 0表示成功（LayUI约定）
        result.put("msg", "查询成功");
        result.put("count", total); // 总记录数
        result.put("data", roleList); // 分页数据列表

        // 输出JSON响应
        PrintWriter out = response.getWriter();
        out.print(result.toString());
        out.flush();
        out.close();
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // POST请求与GET处理逻辑一致
        doGet(request, response);
    }
}
